package com.wodensoft.util.json;

import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.wodensoft.util.json.config.DateFormatProcessor;

/**
 * JSON处理类
 * 
 * @author Woden Wang
 * @since Feb 17, 2011
 */
public class JsonUtil {

    /**
     * json转换
     * 
     * @param resultObj
     * @param jsonConfig
     * @return
     */
    public static Object tranBean2String(Object resultObj, JsonConfig jsonConfig) {
        Object obj;

        if (resultObj instanceof Long || resultObj instanceof Integer || resultObj instanceof String
                || resultObj instanceof Float || resultObj instanceof Double || resultObj instanceof Number) {// 基本类型
            obj = resultObj;
        } else if (resultObj instanceof List || resultObj instanceof Set) {// 集合类型的
            if (jsonConfig == null) {
                obj = (JSONArray.fromObject(resultObj));
            } else {
                obj = (JSONArray.fromObject(resultObj, jsonConfig));
            }
        } else {
            if (jsonConfig == null) {
                obj = (JSONObject.fromObject(resultObj));
            } else {
                obj = (JSONObject.fromObject(resultObj, jsonConfig));
            }
        }

        // logger.debug("转换成json对象:[" + obj + "].");
        return obj;
    }

    /**
     * json转换(默认转换日期类型)
     * 
     * @param resultObj
     * @return
     */
    public static Object tranBean2String(Object resultObj) {
        return tranBean2String(resultObj, createCommonConfig());
    }

    /**
     * 创建通用jsonconfig
     * 
     * @return
     */
    public static JsonConfig createCommonConfig() {
        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(java.util.Date.class, new DateFormatProcessor());
        config.registerJsonValueProcessor(java.sql.Date.class, new DateFormatProcessor());
        config.registerJsonValueProcessor(java.util.Calendar.class, new DateFormatProcessor());
        config.registerJsonValueProcessor(java.util.GregorianCalendar.class, new DateFormatProcessor());
        config.registerJsonValueProcessor(java.sql.Timestamp.class, new DateFormatProcessor());
        return config;
    }

    /**
     * 支持类如:"vars.a"格式的获取json值方式
     * 
     * @param obj
     * @param key
     * @return
     */
    public static Object getObject(JSONObject obj, String key) {
        if (key.indexOf(".") < 0) {// 没有"."
            return obj.get(key);
        }

        String[] keys = key.split("\\.", -1);
        JSONObject tmpObj = obj;
        for (int i = 0; i < keys.length; i++) {
            if (i == keys.length - 1) {// 最后一个
                return tmpObj.get(keys[i]);
            } else {
                tmpObj = tmpObj.getJSONObject(keys[i]);
            }
        }

        return obj.get(key);

    }
}
